﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Helper;
using CatUtils.Utils.SpecialUtils.View;
using RabbitDownload.WebSite.Local.AutoPic;
using RabbitDownload.WebSite.Pixiv;
using RabbitDownload.WebSite.Pixiv.PixivDay;
using System;
using System.Text;
using System.Timers;
using System.Windows.Forms;

namespace RabbitDownload.WebSite.Local
{
    internal class ServerHelper
    {
        private int RunTime = 0;
        private Label TipLocalLable = null;
        private System.Timers.Timer t = new System.Timers.Timer(100);//实例化Timer类，设置间隔时间为10000毫秒；

        public System.ComponentModel.DoWorkEventArgs DoWorkEventArgsE = null;
        private System.ComponentModel.BackgroundWorker LocalBackground = null;

        public void StartRun(Label TipLable, object sender, System.ComponentModel.DoWorkEventArgs e, System.ComponentModel.BackgroundWorker backgroundWorker)
        {
            DoWorkEventArgsE = e;
            LocalBackground = backgroundWorker;

            if (!TipLable.IsHandleCreated)
            {
                Console.WriteLine("控件未创建");
            }

            TipLocalLable = TipLable;

            t.Elapsed += new System.Timers.ElapsedEventHandler(Scanner);//到达时间的时候执行事件；
            t.AutoReset = true;//设置是执行一次（false）还是一直执行(true)；
            t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件；
            Console.WriteLine("启动服务器扫描运行");
        }

        private void Scanner(object sender, ElapsedEventArgs e)
        {
            new ViewAsyncUpdate().LableUpdateTextAsync(TipLocalLable, $"当前时间：{DateTime.Now},距离启动还有{30 - RunTime++}次");

            if (LocalBackground.CancellationPending)
            {
                DoWorkEventArgsE.Cancel = true;
                Console.WriteLine("触发程序结束");
                t.Enabled = false;
                return;
            }

            if (RunTime > 30)
            {
                t.Enabled = false;
                new ViewAsyncUpdate().LableUpdateTextAsync(TipLocalLable, $"当前时间：{DateTime.Now}。启动P站扫描。");

                RunSite();
                System.Environment.Exit(0);
            }
        }

        /// <summary>
        /// 启动站点扫描
        /// </summary>
        private void RunSite()
        {
            new PixivBackgroundRun().ScannerDay();
            new PixivBackgroundRun().ScannerDayFemale();
            new PixivBackgroundRun().ScannerDayMale();
            new PixivBackgroundRun().ScannerWeek();
            new PixivBackgroundRun().ScannerMonthly();
        }
    }
}